<?php

//require('libpgid3_id3v2.so.php');

define("BITRATE_32",1);
define("BITRATE_40",2);
define("BITRATE_48",3);
define("BITRATE_56",4);
define("BITRATE_64",5);
define("BITRATE_80",6);
define("BITRATE_96",7);
define("BITRATE_112",8);
define("BITRATE_128",9);
define("BITRATE_160",10);
define("BITRATE_192",11);
define("BITRATE_224",12);
define("BITRATE_256",13);
define("BITRATE_320",14);

define("SAMPLERATE_44100",0);
define("SAMPLERATE_48000",1);
define("SAMPLERATE_32000",2);

$BITRATE_LOOKUP = array(
	"BITRATE_32" => BITRATE_32,
	"BITRATE_40" => BITRATE_40,
	"BITRATE_48" => BITRATE_48,
	"BITRATE_56" => BITRATE_56,
	"BITRATE_64" => BITRATE_64,
	"BITRATE_80" => BITRATE_80,
	"BITRATE_96" => BITRATE_96,
	"BITRATE_112" => BITRATE_112,
	"BITRATE_128" => BITRATE_128,
	"BITRATE_160" => BITRATE_160,
	"BITRATE_192" => BITRATE_192,
	"BITRATE_224" => BITRATE_224,
	"BITRATE_256" => BITRATE_256,
	"BITRATE_320" => BITRATE_320
);

$SAMPLERATE_LOOKUP = array(
	"SAMPLERATE_44100" => SAMPLERATE_44100,
	"SAMPLERATE_48000" => SAMPLERATE_48000,
	"SAMPLERATE_32000" => SAMPLERATE_32000
);

function readMP3Info($filename) {

	global $BITRATE_LOOKUP,$SAMPLERATE_LOOKUP;
	$return = array();

	//. id3 v2 tags could exist before the first mp3 frame.
	$v1data = readID3v1($filename);
	$v2data = readID3v2($filename);

	$p = fopen($filename,"r");

//	printf("FIRST BYTE: %d\n",ord(fread($p,1)));
//	fseek($p,-1,SEEK_CUR);

	if(is_array($v1data)) {
		$return['v1'] = true;	
	} else {
		$return['v1'] = false;
	}

	if(is_object($v2data) && array_key_exists('total_size',$v2data)) {
		if($v2data->total_size) {
			fseek($p,$v2data->total_size,SEEK_SET);
		}
		$return['v2'] = true;
	} else {
		$return['v2'] = false;
	}

//	printf("tag size: %d\nseek: %d\n",$v2data->total_size,ftell($p));

	for($a = 0; $a < 4; $a++) {
		$bin[$a] = fread($p,1);
	}

	$bitbin = ord($bin[2]);

//	printf("%s\n",decbin($bitbin));

	foreach($BITRATE_LOOKUP as $id => $value) {
		if(($bitbin & ($value << 4)) == ($value << 4)) {
			$return['bitrate'] = str_replace("BITRATE_","",$id);
		}
	}

	foreach($SAMPLERATE_LOOKUP as $id => $value) {
		if(($bitbin & ($value << 2)) == ($value << 2)) {
			$return['samplerate'] = preg_replace("/SAMPLERATE_(\d\d)(\d)\d\d/","\\1.\\2",$id);
		}
	}

	fclose($p);

	return $return;

}


//readMP3Info("/home/tunes/Cascada/Cascada - How Do You Do (Verano Remix).mp3");
//readMP3Info("/home/tunes/test.mp3");
//$mp3 = readMP3Info("/home/tunes/Hinder/Hinder - Lips Of An Angel.mp3");
//print_r($mp3);

?>